import axios from 'axios'
import qs from 'qs';
import ElementUI from 'element-ui';
import router from '../router'

//正式发布时解决此行的注释
//axios.default.baseURL="http://gwstest.metahike.com/gwsapi/index.php";

//请求拦截器
axios.interceptors.request.use(config => {
  //Header中携带其他信息
  if (localStorage.getItem("token") != null) {
    config.headers['token'] = localStorage.getItem("token");
  }
  //console.log("当前token",localStorage.getItem("token"));
   if (config.method == 'post') {
    config.data = qs.stringify(config.data);
  }

  //使用 qs转换后，请求数据将变为 formData形式,否则是 Playload形式
  //config.data = qs.stringify(config.data);
  //console.error("发送请求");
  return config;
}, error => {
  //console.error("发送请求出错",error);
  return Promise.reject(error);
})

//响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.status == 200) {
      if(response.data.code==401){
        ElementUI.Message({message:"登录超时或无权访问,请重新登录!",type:"error"});
        localStorage.removeItem("userinfo");
        localStorage.removeItem("token");

        router.push("/admin/login");
      }
      return response;
    }
  }, error => {
    console.log(error);
    if(error && error.response){
       switch(error.response.status){
         case 504:
         ElementUI.Message({message:"服务器无响应!",type:"error"});
         break;
        case 404:
         ElementUI.Message({message:"服务器不存在此接口!"+error,type:"error"});
        break;
       }
     }
    return Promise.reject(error);
  }
)
